package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsValidacion;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author mk
 */
public class dlg_TipoInsumo extends javax.swing.JDialog {

    private ClsDatabase bd=new ClsDatabase();
    private ClsMetodos metodos=new ClsMetodos();
    private ClsContraladorEventos contraladorEventos=new ClsContraladorEventos();
    private JTable table;
    private dlgInsumoTipo dialog;
    private String id="-1";
    private boolean editarUpdate=false;
    /**
     * Creates new form dlg_TipoInsumo
     * @param parent
     * @param modal
     */
    public dlg_TipoInsumo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public dlg_TipoInsumo(java.awt.Frame parent, boolean modal,JDialog dialog,JTable tblTipoInsumo) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        this.dialog=(dlgInsumoTipo) dialog;
        this.table=tblTipoInsumo;
        metodos._iconJDialog(this);
        Limpiar();
    }
    // <editor-fold desc="CATEGORIA DE INSUMO CODE">
    //TIPO DE INSUMO
    public void Editar(){
        int fila=table.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {//Si no se a seleccionado alguna row de la Tabla hacer...
           Object[][] datos=bd.select("insumo_tipo",
                    "idinsumo_tipo,nombre,abreviatura,estado",
                    "idinsumo_tipo='"+table.getValueAt(fila, 0)+"' ");
            if (datos != null) {
                id=datos[0][0].toString();
                txtDescripcion.setText(datos[0][1].toString());
                txtAbreviaturaTI.setText(datos[0][2].toString());
//                if (datos[0][3].equals("A")) {
//                    tgbActivoTI.setSelected(true);
//                    tgbInactivoTI.setSelected(false);
//                }else{
//                    tgbActivoTI.setSelected(false);
//                    tgbInactivoTI.setSelected(true);
//                }
                txtDescripcion.setSelectionStart(0);
                txtDescripcion.setSelectionEnd(txtDescripcion.getText().length());
                editarUpdate=true;
                setVisible(true);
            } else {
                System.err.println("------------------------>ERROR NO PREVISTO<--------------------------------");
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione una Unidad a editar");
            dispose();
        }
    }

    public void Guardar(){
       String nombreString=txtDescripcion.getText().toString();
        boolean seRepite=true;
        if (editarUpdate) {//Si se presiona EDITAR, entonces el nombre se actualiza, no es un INSERT
            seRepite=false;
        }else{//Verificamos si se repite
            seRepite=bd.verif_repite("SELECT nombre FROM insumo_tipo WHERE nombre='"+nombreString+"'");
        }
        if (!seRepite) {//Verificamos si se Repite el Nombre de Unidad
            if (ClsValidacion.tieneCamposVacios(pnlAgregarTipoInsumo)) {
                JOptionPane.showMessageDialog(null, "Se tiene que llenar todos los campos");
                return;
            }
            String abrev=txtAbreviaturaTI.getText().toString();

            String estadoString="A";
//            if (tgbActivoTI.isSelected()) {
//                estadoString="A";
//            }else{
//                estadoString="I";
//            }

            if (editarUpdate) {
                //UPDATE
                //Realizamos la consulta
                boolean seInserto=bd.update("insumo_tipo",
                        "nombre='"+nombreString+"',abreviatura='"+abrev+"',estado='"+estadoString+"'",
                        "idinsumo_tipo="+id);
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo Actualizar la Tipo de Insumo");
                }
                editarUpdate=false;
            }else{
                //INSERT
                //Realizamos la consulta
                Object[][] datos=bd.select("insumo_tipo", "count(*)", null);
                int orden=Integer.parseInt(datos[0][0].toString()) +1;
                boolean seInserto=bd.insert("insumo_tipo",
                        "nombre,abreviatura,estado,orden",
                        "'"+nombreString+"','"+abrev+"','"+estadoString+"','"+orden+"' ");
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo crear el nuevo Tipo de Insumo");
                }
            }
            dialog._iniciar();
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Ya existe ese Nombre!!!");
            txtDescripcion.requestFocus();
            txtDescripcion.setSelectionStart(0);
            txtDescripcion.setSelectionEnd(txtDescripcion.getText().length());
        }
    }

    public void Cancelar(){
        this.dispose();
    }

    private void Limpiar(){
        txtDescripcion.setText("");
        txtAbreviaturaTI.setText("");
//        tgbActivoTI.setSelected(true);
//        tgbInactivoTI.setSelected(false);
        txtDescripcion.requestFocus();
    }
    // </editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlAgregarTipoInsumo = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtAbreviaturaTI = new javax.swing.JTextField();
        btnGuardarTI = new javax.swing.JButton();
        btnCancelarTI = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos de Tipo de Insumo");

        pnlAgregarTipoInsumo.setBackground(new java.awt.Color(225, 235, 247));
        pnlAgregarTipoInsumo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setOpaque(false);

        jLabel5.setText("Descripción:");

        txtDescripcion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDescripcionKeyTyped(evt);
            }
        });

        jLabel6.setText("Abreviatura:");

        txtAbreviaturaTI.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtAbreviaturaTIKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDescripcion, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtAbreviaturaTI, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 313, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtAbreviaturaTI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pnlAgregarTipoInsumo.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        btnGuardarTI.setText("Guardar");
        btnGuardarTI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarTIActionPerformed(evt);
            }
        });
        pnlAgregarTipoInsumo.add(btnGuardarTI, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 100, -1));

        btnCancelarTI.setText("Cancelar");
        btnCancelarTI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarTIActionPerformed(evt);
            }
        });
        pnlAgregarTipoInsumo.add(btnCancelarTI, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 171, 100, -1));

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlAgregarTipoInsumo.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 210));

        getContentPane().add(pnlAgregarTipoInsumo, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarTIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarTIActionPerformed
        Guardar();
    }//GEN-LAST:event_btnGuardarTIActionPerformed

    private void btnCancelarTIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarTIActionPerformed
        Cancelar();
    }//GEN-LAST:event_btnCancelarTIActionPerformed

    private void txtDescripcionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescripcionKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtDescripcion, 45);
    }//GEN-LAST:event_txtDescripcionKeyTyped

    private void txtAbreviaturaTIKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAbreviaturaTIKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtDescripcion, 45);
    }//GEN-LAST:event_txtAbreviaturaTIKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlg_TipoInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlg_TipoInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlg_TipoInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlg_TipoInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlg_TipoInsumo dialog = new dlg_TipoInsumo(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelarTI;
    private javax.swing.JButton btnGuardarTI;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel pnlAgregarTipoInsumo;
    private javax.swing.JTextField txtAbreviaturaTI;
    private javax.swing.JTextField txtDescripcion;
    // End of variables declaration//GEN-END:variables
}
